package com.vains.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vains.dto.AuthorityDto;
import com.vains.entity.OauthPermission;
import com.vains.entity.OauthUser;
import com.vains.mapper.OauthUserMapper;
import com.vains.service.IOauthPermissionService;
import com.vains.service.IOauthUserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义UserDetailsService
 *
 * @author vains
 * @date 2020/10/21 17:28
 */
@Service
@AllArgsConstructor
public class CustomUserDetailsService extends ServiceImpl<OauthUserMapper, OauthUser> implements UserDetailsService, IOauthUserService {

    private final IOauthPermissionService oauthPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<OauthUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", username);
        wrapper.or();
        wrapper.eq("user_number", username);
        wrapper.or();
        wrapper.eq("user_name", username);
        OauthUser oauthUser = baseMapper.selectOne(wrapper);
        List<OauthPermission> permissions = oauthPermissionService.getPermissionsByUserId(oauthUser.getUserId());
        Set<AuthorityDto> authorities = new HashSet<>();
        for (OauthPermission permission : permissions) {
            AuthorityDto authority = new AuthorityDto(permission.getPermissionUrl());
            authorities.add(authority);
        }
        oauthUser.setUserAuthorities(authorities);
        return oauthUser;
    }

}
